part of base.widgets;

class DebounceButton extends StatelessWidget {
  final VoidCallback? onPressed;
  final Widget? child;
  final int milliseconds;
  final VoidCallback? onLongPress;
  final ValueChanged<bool>? onHover;
  final ValueChanged<bool>? onFocusChange;
  final ButtonStyle? style;
  final FocusNode? focusNode;
  final bool autofocus;

  final Clip clipBehavior;
  final MaterialStatesController? statesController;

  DebounceButton(
      {Key? key,
      required this.onPressed,
      required this.child,
      this.milliseconds = 800,
      this.onLongPress,
      this.onHover,
      this.onFocusChange,
      this.style,
      this.focusNode,
      this.autofocus = false,
      this.clipBehavior = Clip.none,
      this.statesController})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return UnconstrainedBox(
        child: TextButton(
      onPressed: onPressed == null
          ? null
          : onPress(fun: onPressed, milliseconds: milliseconds),
      onLongPress: onLongPress,
      onHover: onHover,
      onFocusChange: onFocusChange,
      style: style,
      focusNode: focusNode,
      autofocus: autofocus,
      clipBehavior: clipBehavior,
      statesController: statesController,
      child: child!,
    ));
  }

  final TimeData timeData = TimeData();

  bool doubleClick(int milliseconds) {
    DateTime? lastPressedAt = timeData.lastPressedAt;
    if (lastPressedAt == null ||
        DateTime.now().difference(lastPressedAt) >
            Duration(milliseconds: milliseconds)) {
      timeData.lastPressedAt = DateTime.now();
      return false;
    }
    return true;
  }

  Function() onPress({Function()? fun, int milliseconds = 800}) {
    return () {
      if (doubleClick(milliseconds)) {
        return;
      }
      fun?.call();
    };
  }
}

class TimeData {
  DateTime? lastPressedAt;
}
